package com.aorise.controller.system;

import com.aorise.exception.DataValidationException;
import com.aorise.model.response.UserInfoRes;
import com.aorise.model.system.User;
import com.aorise.model.request.RegisterUserReq;
import com.aorise.model.response.UserListRes;
import com.aorise.service.system.UserService;
import com.aorise.utils.*;
import com.aorise.utils.json.JsonResponseData;
import io.swagger.annotations.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.http.MediaType;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * @Auther: zhouhao
 * @Date: 2019/5/16
 * @Description:    用户相关接口
 */
@Slf4j
@Api(description = "用户相关接口")
@RestController
@Validated
@RequestMapping("api/user")
@RequiresPermissions("YHZHGL")
public class UserController {

    @Autowired
    UserService userService;

    /**
     * 添加用户
     * HTTP 方式：GET
     * API 路径：/api/user/
     * 方法名：register
     * 方法返回类型：String
     */
    @ApiOperation(value = "添加用户", httpMethod = "POST", response = String.class, notes = "添加用户")
    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public String register(@RequestBody @Validated(value = {UserService.class}) RegisterUserReq userReq,BindingResult result){
        try {
            if (result.hasErrors()) {
                return JsonResponseData.ofMessage(StatusDefine.DATA_FORMAT_ERROR, result.getFieldError().getDefaultMessage());
            }
            String account = userReq.getAccount();
            Integer userType = userReq.getUserType()==null?1:userReq.getUserType();
            List<User> users = userService.selectByAccount(account, userType);
            if(CollectionUtils.isNotEmpty(users)){
                return new JsonResponseData(Boolean.FALSE, StatusDefineMessage.GetMessage(StatusDefine.U_EXIST_USER),
                        StatusDefine.U_EXIST_USER, "", null).toString();
            }
            if(userService.addUser(userReq)){
                return JsonResponseData.ofSuccess(null);
            }
        }catch (DataValidationException e) {
            log.error(
                    "controller:UserController. function:register...msg: register DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:UserController. function:register...msg: register DataAccessException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:UserController. function:register. msg:register Exception");
            log.error(e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
        return JsonResponseData.ofFailure();
    }

    /**
     * 密码重置
     * HTTP 方式：GET
     * API 路径：/api/user/
     * 方法名：reset
     * 方法返回类型：String
     */
    @ApiOperation(value = "密码重置", httpMethod = "GET", response = String.class, notes = "密码重置")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID",  paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "token", value = "token",  paramType = "query", dataType = "string")

    })
    @RequestMapping(value = "/reset", method = RequestMethod.GET,produces="application/json")
    public String reset(Integer userId,String token) {
        try {
            if(userId == null){
                throw new DataValidationException("用户ID不能为空");
            }
            if(userService.resetPwdByUserId(userId)){
                return JsonResponseData.ofSuccess(null);
            }
        }catch (DataValidationException e) {
            log.error(
                    "controller:UserController. function:reset...msg: reset DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:UserController. function:reset...msg: reset DataAccessException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:UserController. function:reset. msg:reset Exception");
            log.error(e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
        return JsonResponseData.ofFailure();
    }

    /**
     * 用户删除
     * HTTP 方式：DELETE
     * API 路径：/api/user/
     * 方法名：deleteUser
     * 方法返回类型：String
     */
    @ApiOperation(value = "用户删除", httpMethod = "DELETE", response = String.class, notes = "用户删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID",  paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "token", value = "token",  paramType = "query", dataType = "string")

    })
    @RequestMapping(value = "/delete", method = RequestMethod.DELETE,produces="application/json")
    public String deleteUser(Integer userId,String token){
        try {
            if(userId == null){
                throw new DataValidationException("用户ID不能为空");
            }
            String result =userService.isWorkUser(userId);
            if(StringUtils.isNotBlank(result)){
                return new JsonResponseData(false, "", StatusDefine.PERSON_DEL_ERROR,
                        result, null).toString();
            }

            if(userService.deleteUser(userId)){
                return JsonResponseData.ofSuccess(null);
            }
        }catch (DataValidationException e) {
            log.error(
                    "controller:UserController. function:deleteUser...msg: deleteUser DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:UserController. function:deleteUser...msg: deleteUser DataAccessException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:UserController. function:deleteUser. msg:deleteUser Exception");
            log.error(e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
        return JsonResponseData.ofFailure();
    }

    /**
     * 用户编辑
     * HTTP 方式：POST
     * API 路径：/api/user/
     * 方法名：updateUser
     * 方法返回类型：String
     */
    @ApiOperation(value = "用户编辑", httpMethod = "POST", response = String.class, notes = "用户编辑")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "用户ID",  paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "/update", method = RequestMethod.POST,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String updateUser(@RequestBody RegisterUserReq userReq,Integer userId){
        DataValidation validation =new DataValidation();
        try {
            validation.chkLength(userReq.getUsername(),1,20,"姓名不能为空且长度需要在1和20之间");
            validation.chkLength(userReq.getDeptId(),0,20,"职务不能为空且长度不能超过20位");
            validation.chkLength(userReq.getPhone(),11,11,"手机号码必须为11位数");
            validation.cheFormat(DataValidationUtil.V_MOBILENULL,userReq.getPhone(),"手机号码必须为整数");
            if (userReq.getRoleId() == null) {
                throw new DataValidationException("角色不能为空");
            }
            if (userReq.getOrgId() == null) {
                throw new DataValidationException("组织架构不能为空");
            }
            if (userId == null) {
                throw new DataValidationException("用户ID不能为空");
            }
            if(userService.updateUser(userReq,userId)){
                return JsonResponseData.ofSuccess(null);
            }
        }catch (DataValidationException e) {
            log.error(
                    "controller:UserController. function:updateUser...msg: updateUser DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:UserController. function:updateUser...msg: updateUser DataAccessException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:UserController. function:updateUser. msg:updateUser Exception");
            log.error(e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
        return JsonResponseData.ofFailure();
    }

    /**
     * 用户列表
     * HTTP 方式：GET
     * API 路径：/api/user/
     * 方法名：userList
     * 方法返回类型：String
     */
    @ApiOperation(value = "用户列表", httpMethod = "GET", response = String.class, notes = "用户列表")
    @RequestMapping(value = "/userList", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String userList(UserListRes userRes){
        Page userPageInfo =null;
        try {
            userPageInfo = userService.selectUserList(userRes);
        }catch (DataValidationException e) {
            log.error(
                    "controller:UserController. function:userList...msg: userList DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:UserController. function:userList...msg: userList DataAccessException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:UserController. function:userList. msg:userList Exception");
            log.error(e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
        return JsonResponseData.ofSuccess(userPageInfo);
    }

    /**
     * 个人中心
     * HTTP 方式：GET
     * API 路径：/api/userInfo/
     * 方法名：userList
     * 方法返回类型：String
     */
    @ApiOperation(value = "用户详情", httpMethod = "GET", response = String.class, notes = "个人中心")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "1",  paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "token", value = "token",  paramType = "query", dataType = "string")
    })
    @RequestMapping(value = "/userInfo", method = RequestMethod.GET,produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String userInfo(Integer userId,String token){
        UserInfoRes userInfoRes =null;
        try {
            userInfoRes = userService.selectUserInfoByUserId(userId);
        }catch (DataValidationException e) {
            log.error(
                    "controller:UserController. function:userInfo...msg: userInfo DataValidationException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DATA_FORMAT_ERROR,
                    e.getMessage(), null).toString();
        }catch (DataAccessException e) {
            log.error(
                    "controller:UserController. function:userInfo...msg: userInfo DataAccessException");
            log.error("error:" + e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.DB_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.DB_ERROR), null).toString();
        } catch (Exception e) {
            log.error(
                    "controller:UserController. function:userInfo. msg:userInfo Exception");
            log.error(e.getMessage());
            return new JsonResponseData(false, "", StatusDefine.SYS_ERROR,
                    StatusDefineMessage.GetMessage(StatusDefine.SYS_ERROR), null).toString();
        }
        return JsonResponseData.ofSuccess(userInfoRes);
    }

}
